package com.linran.utils.jackson;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeType;
import lombok.Getter;
import lombok.Setter;

import java.io.IOException;

/**
 * jsonNode
 *
 * @author lin
 * @date 2020-08-12 15:11
 */
public class JsonNodePlay {
    public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    public static void main(String[] args) throws IOException {
        Car car = new Car("xiandai", 4);
        String s = OBJECT_MAPPER.writeValueAsString(car);
        System.out.println(s);
        //字符串转jsonNode
        JsonNode jsonNode = OBJECT_MAPPER.readTree(s);
        //@link com.fasterxml.jackson.databind.node.JsonNodeType
        JsonNodeType nodeType = jsonNode.getNodeType(); //OBJECT

        JsonNode brand = jsonNode.get("brand"); //NODETYPE:STRING
        String brandValue = brand.asText();
        JsonNode doors = jsonNode.get("doors"); //NODETYPE:NUMBER
        int i = doors.asInt();

        //java对象转JsonNode
        JsonNode carJsonNode = OBJECT_MAPPER.valueToTree(car);
        //JsonNode转java对象
        Car car1 = OBJECT_MAPPER.treeToValue(carJsonNode, Car.class);
    }
}

@Setter
@Getter
class Car {
    public Car() {
    }

    public Car(String brand, Integer doors) {
        this.brand = brand;
        this.doors = doors;
    }

    private String brand;
    private Integer doors;
}
